package com.binguo.api.controller;

import com.binguo.api.form.FileForm;
import com.binguo.api.result.Result;
import com.binguo.api.result.ResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping
public class FileController {

    private static Logger logger = LoggerFactory.getLogger(FileController.class);

    private List<Integer> directoryCreatedShopIdList = new ArrayList<>();

    private BASE64Decoder decoder = new BASE64Decoder();

    private String ipAddress;


    public FileController(){
        this.ipAddress = System.getenv().get("ipAddress");
        File file = new File("/usr/local/nginx/html/images/file");
        if (!file.exists()) {
            file.mkdir();
        }
    }

    @PostMapping("/api/file/upload")
    public Result upload(@RequestBody FileForm fileForm) {
        long startTime = System.currentTimeMillis();
        logger.info("startTime=" + startTime);
        StringBuffer filePathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/file/");
        filePathStringBuffer.append(fileForm.getShopId());

        if (!directoryCreatedShopIdList.contains(fileForm.getShopId())) {
            File dir = new File(filePathStringBuffer.toString());
            directoryCreatedShopIdList.add(fileForm.getShopId());
            if (!dir.exists()) {
                dir.mkdir();
            }
        }

        String newFileName = filePathStringBuffer.append("/").append(fileForm.getSerialNumber()).append(".png").toString();

        try {

            byte[] bytes1 = decoder.decodeBuffer(fileForm.getFileContent());
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);

            File f1 = new File(newFileName);
            ImageIO.write(bi1, "png", f1);


            logger.info("上传成功:newFileName==" + newFileName);

            StringBuffer imgUrl = new StringBuffer("http://")
                    .append(ipAddress)
                    .append(":8019/images/file/")
                    .append(fileForm.getShopId())
                    .append("/").append(fileForm.getSerialNumber()).append(".png");

            return ResultGenerator.genSuccessResult(imgUrl);

        } catch (Exception e) {
            logger.error("{}", e);
        }

        return ResultGenerator.genFailResult("上传失败");
    }
}
